package com.it.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.remoting.RemoteAccessException;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
@Slf4j
public class SpringRetryService {
    /**
     * 重试所调用方法
     *
     * delay=2000L表示延迟2秒 multiplier=2表示两倍 即第一次重试2秒后,第二次重试4秒后,第三次重试8秒后
     * @return
     */
    @Retryable(value = {RemoteAccessException.class}, maxAttempts = 3, backoff = @Backoff(delay = 2000L, multiplier = 2))
    public boolean call(Integer param) {
        return retryMethod(param);
    }

    /**
     * 超过最大重试次数或抛出没有指定重试的异常
     * @param e
     * @param param
     * @return
     */
    @Recover
    public boolean recover(Exception e, Integer param) {
        log.info("请求参数为: ", param);
        log.info("超过最大重试次数或抛出没有指定重试的异常, e = {} ", e.getMessage());
        return false;
    }

    public static boolean retryMethod(Integer param) {
        int i = new Random().nextInt(param);
        log.info("随机生成的数:{}", i);

        if (1 == i) {
            log.info("为1,返回true.");
            return true;
        } else if (i < 1) {
            log.info("小于1,抛出参数异常.");
            throw new IllegalArgumentException("参数异常");
        } else if (i > 1 && i < 10) {
            log.info("大于1,小于10,抛出参数异常.");
            return false;
        } else {
            //为其他
            log.info("大于10,抛出自定义异常.");
            throw new RemoteAccessException("大于10,抛出自定义异常");
        }
    }
}